<?php

foreach($argv as $inputArgument) {
    if ($inputArgument === $argv[0]) {//ignore first
        continue;
    } else if (preg_match("/^--expansionID=([0-9]+)$/", $inputArgument, $matches)) {
        $expansionId = $matches[1];
    } else if (preg_match("/^--cardDataFolder=(.+)$/", $inputArgument, $matches)) {
        $inputFolder=$matches[1];
    }
}

if (!isset($expansionId)) {
    echo "expansionID is not set\n";
    exit -1;
}

if (!isset($inputFolder)) {
    echo "cardDataFolder is not set\n";
    exit -1;
} else if (!is_dir($inputFolder)) {
    echo "cardDataFolder \"$inputFolder\" is not a directory.";
    exit -1;
}

$inputFiles_unfiltered = scandir($inputFolder);
$inputFiles_filtered = array();

foreach ($inputFiles_unfiltered as $inputFile_unfiltered) {
    if (preg_match("/^[0-9]+\.json$/", $inputFile_unfiltered)) {
        array_push($inputFiles_filtered, $inputFile_unfiltered);
    }
}

unset($inputFiles_unfiltered);

if(empty($inputFiles_filtered)) {
    echo "No valid json file found in \"$inputFolder\"";
    exit -1;
}

foreach ($inputFiles_filtered as $inputFile) {
    $string = file_get_contents($inputFolder.'/'.$inputFile);
    $json_a=json_decode($string,true);

    echo "\n/*".$inputFile."*/\n";

    //Find artist ID or insert new artist.
    if (isset($json_a['artist'])) {
        echo( 
        "INSERT INTO `Artist` (`name`) VALUES ('".$json_a['artist']."')\n"
        ."  ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id);\n"
        ."SET @artist = LAST_INSERT_ID();\n"
        );
    } else {
        echo "No valid artist set in file \"$inputFile\"";
        exit -1;
    }
    
    //Insert new Card basic info
    if (isset($json_a['card number'], $json_a['rarity'])) {
        echo(
        "INSERT INTO `Card` (`expansion`, `cardnumber`, `Artist_Id`, `Rarity`)\n"
        ." VALUES (\"$expansionId\", \"".$json_a['card number']."\", @artist, \"".$json_a['rarity']."\")\n"
        ." ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id);\n"
        ."SET @cardId = LAST_INSERT_ID();\n"
        );    
    } else {
        if (!isset($json_a['card number'])) {
            echo "No card number set in file \"$inputFile\"";
        }
        if (!isset($json_a['rarity'])) {
            echo "No rarity set in file \"$inputFile\"";
        }
        exit -1;
    }
    
    //Insert cardside
    if (isset($json_a['name'])) {
        echo(
        "INSERT INTO `Cardside` (`Cardname`, `Manacost`, `Converted_Manacost`, `Flavortext`, `Power`, `Toughness`, `Loyalty`, `Watermark`)\n"
        ." VALUES (\"".$json_a['name']."\",\n"
        ."        ".(isset($json_a['manacost']) ? "\"".$json_a['manacost']."\"" : "\"\"").",\n"
        ."        ".(isset($json_a['converted manacost']) ? "\"".$json_a['converted manacost']."\"" : 0).",\n"
        ."        ".(isset($json_a['flavor text']) ? "\"".str_replace("\"", "\\\"", $json_a['flavor text'])."\"" : "\"\"").",\n"
        ."        ".(isset($json_a['power']) ? "\"".$json_a['power']."\"" : "\"\"").",\n"
        ."        ".(isset($json_a['toughness']) ? "\"".$json_a['toughness']."\"" : "\"\"").",\n"
        ."        ".(isset($json_a['loyalty']) ? "\"".$json_a['loyalty']."\"" : "0").",\n"
        ."        ".(isset($json_a['watermark']) ? "\"".$json_a['atermark']."\"" : "\"\"")."\n"
        ."       )\n"
        ." ON DUPLICATE KEY UPDATE cardside_id=LAST_INSERT_ID(cardside_id);\n"
        ."SET @cardsideId = LAST_INSERT_ID();\n"
        );
    } else {
        echo "No card name set in file \"$inputFile\"";
        exit -1;
    }
    
    //link card and cardside
    echo(
    "INSERT INTO `Card_Cardside` (`Card_Id`, `Cardside_Id`, `location`)\n"
    ." VALUES(@cardId, @cardsideId, \"front\");\n"
    );
    
    //link card, cardside and multiverseId
    echo(
    "INSERT INTO `card_externalid` (`Card_ID`, `Cardside_Id`, `multiverse_ID`)\n"
    ." VALUES(@cardId, @cardsideId, ".substr($inputFile, 0, -5).");\n"
    );
    
    //Insert types
    if (isset($json_a['types'])) {
        $types = split(' ', $json_a['types']);
        $priority = 0;
        foreach($types as $key=>$type) {
            echo(
            "INSERT INTO `Type` (`name`) VALUES (\"$type\")\n"
            ." ON DUPLICATE KEY UPDATE Type_Id=LAST_INSERT_ID(Type_Id);\n"
            ."INSERT IGNORE INTO `Cardside_Type` (`Cardside_Id`, `Type_Id`, `priority`)\n"
            ." VALUES(@cardsideId, LAST_INSERT_ID(), \"$key\");\n"
            );
        }
    } else {
        echo "No type set in file \"$inputFile\"";
        exit -1;
    }
    
    //Insert sub-types
    if (isset($json_a['subtypes'])) {
        $subtypes = split(' ', $json_a['subtypes']);
        $priority = 0;
        foreach($subtypes as $key=>$subtype) {
            echo(
            "INSERT INTO `Subtype` (`name`) VALUES (\"$subtype\")\n"
            ." ON DUPLICATE KEY UPDATE Subtype_Id=LAST_INSERT_ID(Subtype_Id);\n"
            ."INSERT IGNORE INTO `Cardside_Subtype` (`Cardside_Id`, `Subtype_Id`, `priority`)\n"
            ." VALUES(@cardsideId, LAST_INSERT_ID(), \"$key\");\n"
            );
        }
    }
    
    //Insert card text
    if (isset($json_a['card text']) && is_array($json_a['card text'])) {
        $previousCardText = "";
        $priority = 0;
        foreach($json_a['card text'] as $cardText) {
            $cardText = str_replace("\"", "\\\"", $cardText);
        
            if ($cardText === $previousCardText)
                $priority += 1;
            else
                $priority = 0;
        
            echo(
            "INSERT INTO `Card_text` (`text`) VALUES (\"$cardText\")\n"
            ." ON DUPLICATE KEY UPDATE card_text_ID=LAST_INSERT_ID(card_text_ID);\n"
            ."INSERT IGNORE INTO `Cardside_Text` (`Cardside_Id`, `Text_Id`, `priority`)\n"
            ." VALUES(@cardsideId, LAST_INSERT_ID(), $priority);\n"
            );
            
            $previousCardText = $cardText;
        }
    }
}
?>
